//
// Created by wangyg98 on 2025/4/28.
//

#include "ResourceManager.h"
#include <sstream>
#include <iostream>

// 初始化静态成员变量
std::unordered_map<std::string, ResourceManager::CharacterResources> ResourceManager::resources;

void ResourceManager::LoadResources(const std::string& path, int num, const std::string& character_type){
    auto& res = resources[character_type];
    if(res.loaded) return; //如果加载过直接返回

    for (size_t i = 0; i < num; i++) {
        std::stringstream ssleft;
        ssleft << path<<"\\"<<character_type<<"_left_" << i << ".png";
        std::string filename_left = ssleft.str();

        std::stringstream ssright;
        ssright << path<<"\\"<<character_type<<"_right_" << i << ".png";
        std::string filename_right = ssright.str();

        res.framesLeft.emplace_back(std::make_unique<IMAGE>());
        loadimage(res.framesLeft.back().get(), filename_left.c_str());

        res.framesRight.emplace_back(std::make_unique<IMAGE>());
        loadimage(res.framesRight.back().get(), filename_right.c_str());
    }

    res.loaded = true;
}

const std::vector<std::unique_ptr<IMAGE>>& ResourceManager::GetFramesLeft(
        const std::string& characterType) {

    auto it = resources.find(characterType);
    if (it == resources.end() || !it->second.loaded) {
        throw std::runtime_error(characterType + " resources not loaded yet!");
    }
    return it->second.framesLeft;
}

const std::vector<std::unique_ptr<IMAGE>>& ResourceManager::GetFramesRight(
        const std::string& characterType) {

    auto it = resources.find(characterType);
    if (it == resources.end() || !it->second.loaded) {
        throw std::runtime_error(characterType + " resources not loaded yet!");
    }
    return it->second.framesRight;
}

void ResourceManager::ClearResources(const std::string& characterType) {
    resources.erase(characterType);
}

void ResourceManager::ClearAllResources() {
    resources.clear();
}


